package com.chd.ledger_server.controller;

import com.chd.ledger_server.entity.SysUsers;
import com.chd.ledger_server.service.SysUsersService;
import com.chd.ledger_server.domain.PageDto;
import com.chd.ledger_server.domain.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统用户表(SysUsers)表控制层
 *
 * @author makejava
 * @since 2025-07-24 12:42:03
 */
@RestController
@RequestMapping("/sysUsers")
@CrossOrigin
public class SysUsersController {
    /**
     * 服务对象
     */
    @Resource
    private SysUsersService sysUsersService;

    /**
     * 分页查询
     *
     * @param pageDto 分页请求实体，仅包含SysUsers实体+分页数据
     * @return SysUsers列表
     */
    @PostMapping("/queryByPage")
    public Result queryByPage(@RequestBody PageDto pageDto) {
        PageInfo list = sysUsersService.queryAllSysUserssByPage(pageDto);
        if (list.getList().isEmpty()) return Result.buildFail("未查到相关信息！");
        return Result.buildSuccess(list);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/queryById")
    public Result queryById(Integer id) {
        SysUsers entity = this.sysUsersService.queryById(id);
        if (entity == null) {
            return Result.buildFail("未找到记录");
        }
        return Result.buildSuccess(entity);
    }

    /**
     * 新增数据
     *
     * @param sysUsers 实体
     * @return 新增结果
     */
    @PostMapping("/add")
    public Result add(@RequestBody SysUsers sysUsers) {
        SysUsers result = this.sysUsersService.insert(sysUsers);
        return Result.buildSuccess(result);
    }

    /**
     * 编辑数据
     *
     * @param sysUsers 实体
     * @return 编辑结果
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody SysUsers sysUsers) {
        SysUsers result = this.sysUsersService.update(sysUsers);
        if (result == null) {
            return Result.buildFail("更新失败，记录不存在");
        }
        return Result.buildSuccess(result);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/deleteById")
    public Result deleteById(Integer id) {
        boolean success = this.sysUsersService.deleteById(id);
        if (success) {
            return Result.buildSuccess("删除成功");
        } else {
            return Result.buildFail("删除失败，记录不存在");
        }
    }

    /**
     * 用户登录接口
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result login(@RequestBody SysUsers sysUsers) {
        System.out.println(sysUsers);
        String result = sysUsersService.login(sysUsers.getUserName(),sysUsers.getUserPsw());
        // 根据返回消息判断登录是否成功
        if ("登录成功".equals(result)) {
            SysUsers user = sysUsersService.queryUser(sysUsers.getUserName(), sysUsers.getUserPsw()).get(0);
            return Result.buildSuccess(user);
        } else {
            return Result.buildFail(result);
        }
    }
}
